<template>
    <div>
        <tablePaging :tableItem="tableItem" :operationItem="operationItem">
            <template v-slot:customTableHeader>
            </template>
        </tablePaging>
        <el-dialog v-model="addVisible" title="类型管理">
            <div>
                <div>
                    <el-button v-hasPermi="[$button.traincourseBankTypeadd || null]" class="add-type" type="primary"
                        @click="tableType.push({ input: '', apiType: 'add' })" :icon="Plus">新增类型</el-button>
                </div>
                <!--  :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" -->
                <el-table :data="tableType" style="width: 100%;max-height:440px;overflow-y:scroll;">
                    <el-table-column label="类型名称">
                        <template #default="scope">
                            <span v-if="scope.row.input == undefined">{{ scope.row.name }}</span>
                            <el-input v-else maxlength="30" v-model="scope.row.input" placeholder="请输入类型名称" />
                        </template>
                    </el-table-column>
                    <el-table-column label="默认题库">
                        <template #default="scope">
                            <el-radio v-model="defaultFlag" :label="scope.row.id" size="large">{{ '' }}</el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="230">
                        <template #default="scope">
                            <el-button v-hasPermi="[$button.traincourseBankTypeedit || null]" link type="primary"
                                size="small" v-if="scope.row.input === undefined"
                                @click="primaryHandle('edit', scope)">修改</el-button>
                            <el-button v-hasPermi="[$button.traincourseBankTypeedit || null]"
                                v-if="scope.row.input != undefined" @click="primaryHandle('save', scope)" link
                                type="primary" size="small">保 存</el-button>
                            <el-button v-hasPermi="[$button.traincourseBankTypedisable || null]"
                                v-if="scope.row.disableFlag && scope.row.input === undefined" link type="primary"
                                size="small" @click="dangerType('dis', scope, 0)">启用</el-button>
                            <el-button v-hasPermi="[$button.traincourseBankTypedisable || null]"
                                v-if="!scope.row.disableFlag && scope.row.input === undefined" link type="danger"
                                size="small" @click="dangerType('dis', scope, 1)">禁用</el-button>
                            <el-button v-hasPermi="[$button.traincourseBankTyperemove || null]" link type="danger"
                                size="small" @click="dangerType('del', scope)">{{
                                    scope.row.input != undefined ? '取消' : '删除' }}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <!-- <el-button @click="dialogVisible = false">返回</el-button> -->
                    <el-button type="primary" @click="typeConfirm"> 确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <!--  -->
        <el-dialog v-model="courseVisible" :title="requestAddEdit.title" @close="requestAddEditInit">
            <el-form :rules="rules" ref="ruleFormRef" :model="requestAddEdit" label-width="120px">
                <el-form-item label="课程名称" prop="name">
                    <el-input maxlength="30" v-model="requestAddEdit.name" placeholder="请输入课程名称" />
                </el-form-item>
                <el-form-item label="序号" prop="orderNum">
                  <el-input type="number" v-model.number="requestAddEdit.orderNum" placeholder="请输入序号" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="courseVisible = false">取 消</el-button>
                    <el-button type="primary" @click="courseConfirm(ruleFormRef)"> 确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 价格管理 -->
        <el-dialog v-model="data.priceVisible" :title="'价格管理'" @close="">
            <div class="price-el-button">
                <el-button v-hasPermi="[$button.traincoursePriceadd || null]" @click="priceAddHandle" type="primary" style="height: 32px;float: right;padding:11px 20px">
                    <el-icon class="el-icon--right" style="margin-right: 5px;">
                        <Plus />
                    </el-icon>
                    新增价格
                </el-button>
                <el-table :data="data.priceTableData" style="width: 100%">
                    <el-table-column label="价格（元）">
                        <template #default="scope">
                            <span v-if="scope.row['static'] == 'detail'">{{ scope.row['price'] }}</span>
                            <el-input @input="scope.row['price']=onlyNumber(scope.row['price'])" maxlength="20" v-else style="width: 200px;" v-model="scope.row['price']"
                                placeholder="请输入课程价格" />
                        </template>
                    </el-table-column>
                    <el-table-column label="时长（天）">
                        <template #default="scope">
                            <span v-if="scope.row['static'] == 'detail'">{{ scope.row['dayAmount'] }}</span>
                            <el-input @input=" scope.row['dayAmount']=IntegerOneHundred( scope.row['dayAmount'],99999,1)" maxlength="20" v-else style="width: 200px;" v-model="scope.row['dayAmount']"
                                placeholder="请输入时长" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button v-hasPermi="[$button.traincoursePriceedit || null]" link v-if="scope.row['static'] == 'detail'" @click="priceEditHandle(scope)"
                                type="primary" size="small">修改</el-button>
                            <el-button link v-else @click="priceSaveHandle(scope)" type="primary"
                                size="small">保存</el-button>
                            <el-button v-hasPermi="[$button.traincoursePriceremove || null]" link v-if="scope.row['static'] == 'detail'" @click="priceDelHandle(scope)"
                                type="danger" size="small">删除</el-button>
                            <el-button link v-else type="danger" @click="closeInputHandle(scope)"
                                size="small">取消</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <!-- <el-button @click="data.priceVisible = false">取 消</el-button> -->
                    <el-button type="primary" @click="data.priceVisible = false"> 确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import $button from '@/button'
import tablePaging from '@/views/common/component/table-paging'
import { onMounted, reactive, inject, ref, getCurrentInstance } from 'vue'
import {
    tableItem, operationItem, courseAddApi, coursePutApi, courseDelApi, typeListApi,
    typeAddApi, typePutApi, typeDelApi, typeDisApi, confListApi, defaultBankApi, confDelApi,
    confAddApi, confUpdateApi
} from './const.js'
import { Delete, Edit, Plus, Share, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {IntegerOneHundred,numberTwoPoint, onlyNumber} from'@/utils/checkInput'
const data = reactive({
    priceRequest: {
        "dayAmount": "", //天数
        "price": "", //价格
        "courseId": 24 //课程id
    },
    priceVisible: false,
    priceTableData: [

    ]
})
const { ctx, proxy } = getCurrentInstance();
const addVisible = ref(false)
const courseVisible = ref(false)
const ruleFormRef = ref('')
const defaultFlag = ref(false)
const rules = reactive({
    name: [
        { required: true, message: '请输入课程名称', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
  orderNum: [{ required: true, message: '请输入序号', trigger: 'blur' },]
})

const requestAddEdit = reactive({
    "name": "",
    "parentId": 0,
    title: '新增课程',
    type: 'add'// subAdd新增下级 add新增课程 edit 修改
})
const requestType = reactive({
    "courseId": "",
    "disableFlag": null,
})
let tableType = ref([])
//
onMounted(() => {
})
const typeConfirm = () => {
    if (defaultFlag.value) {
        defaultBankApi({ defaultFlag: 1, id: defaultFlag.value }).then((res) => {
            tableItem.pageInfo.paging();
        })
    } else {
        tableItem.pageInfo.paging();
    }
    addVisible.value = false
}
const priceAddHandle = () => {
    data.priceTableData.push({
        "dayAmount": '', //天数
        "price": '', //价格
        "courseId": data.priceRequest['courseId'], //课程id
        static: 'add',
    })
}
const priceEditHandle = (scope) => {
    scope.row.static = 'edit'
}
const priceSaveHandle = async (scope) => {
    let request = {
        "dayAmount": '', //天数
        "price": '', //价格
        "courseId": null,//课程id
        "id": null,
    }
    for (const key in request) {
        request[key] = scope.row[key]
    }
    if(request.price === '') {return ElMessage.warning('请输入价格')}
    if(!request.dayAmount) {return ElMessage.warning('请输入时长')}
    if (scope.row['static'] == 'add') {
        await confAddApi(request).then((res) => { ElMessage.success('新增成功'); scope.row['static'] = 'detail'; priceList() })
    } else {
        await confUpdateApi(request).then((res) => { ElMessage.success('修改成功'); scope.row['static'] = 'detail'; priceList() })
    }
    tableItem.pageInfo.paging();
}
const priceDelHandle = (scope) => {
    ElMessageBox.confirm(
        `确定删除?`,
        '提示',
        {
            callback: (action) => {
                if (action != 'confirm') {return}
                    confDelApi(scope.row['id']).then((res)=>{
                        ElMessage.success('删除成功')
                        priceList()
                    })
            }
        }
    )
}
const closeInputHandle = (scope) => {
    if (scope.row['static'] === 'add') {
        data.priceTableData.splice(scope.$index, 1)
    }else{
        scope.row['static']='detail'
        priceList()
    }
    // scope.row['static'] = 'detail'
}
const requestAddEditInit = () => {
    requestAddEdit.name = ""
    requestAddEdit.parentId = 0
    // requestAddEdit.title = "新增课程"
    requestAddEdit.type = "add"
    if (ruleFormRef.value) { ruleFormRef.value.clearValidate() }
}
const initTableDataType = () => {
    defaultFlag.value = false
    typeListApi(requestType).then(res => {
        tableType.value = res.rows || []
        tableType.value.map((item) => {
            item.defaultFlag ? defaultFlag.value = item.id : ''
        })
    })
};
const dangerType = (type, scope, dis) => {
    const row = scope.row
    if (!row.id) {
        tableType.value.splice(scope.$index, 1)
        return
    }
    if (row.input != undefined) {
        initTableDataType();
        return
    }
    switch (type) {
        case 'del': typeDelApi(row.id).then(res => { ElMessage.success('操作成功'); initTableDataType() })
            break;
        case 'dis':
            typeDisApi({ id: row.id, disableFlag: dis || 0 }).then(res => { ElMessage.success('操作成功'); initTableDataType() })
            break;
        default: ''
    }
};
const primaryHandle = (type, scope) => {
    if (type == 'edit') { scope.row.input = scope.row.name }
    if (type == 'save') {
        if (!scope.row.input) { ElMessage.warning('请输入类型名称'); return }
        if (scope.row.apiType == 'add') {
            typeAddApi({ name: scope.row.input, courseId: requestType.courseId }).then(res => {
                ElMessage.success('操作成功'); initTableDataType()
                scope.row.name = scope.row.input, scope.row.input = undefined
            })
        } else {
            typePutApi({ name: scope.row.input, id: scope.row.id }).then(res => {
                ElMessage.success('操作成功'); initTableDataType()
            })
        }

    }
};
const courseAddEdit = (row, type) => {
    requestAddEdit.type = type || 'add'
    // 是否为课程添加
    typeof row == 'string' ? requestAddEdit.type = row : (requestAddEdit.parentId = row.id || 0, requestAddEdit.id = row.id, requestAddEdit.name = row.name || '',requestAddEdit.orderNum = row.orderNum || '')
    switch (requestAddEdit.type) {
        case 'add': requestAddEdit.title = '新增课程';requestAddEdit.orderNum = ''
            break;
        case 'subAdd': requestAddEdit.title = '新增下级'; requestAddEdit.name = '';requestAddEdit.orderNum = ''
            break;
        case 'edit': requestAddEdit.title = '修改课程'
            break;
        default: ''
    }
    courseVisible.value = true
}
const courseConfirm = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid, fields) => {
        if (!valid) { return }
        if (requestAddEdit.type == 'edit') {
            const { name, id, orderNum} = requestAddEdit
            coursePutApi({ name, id, orderNum}).then(res => {
                ElMessage.success('操作成功'); courseVisible.value = false; tableItem.pageInfo.paging()
            })
        } else {
            const { name, parentId, orderNum } = requestAddEdit
            courseAddApi({ name, parentId, orderNum }).then(res => {
                ElMessage.success('操作成功'); courseVisible.value = false; tableItem.pageInfo.paging()
            })
        }
    })
}
const priceHandle = () => {

}
operationItem.menuArray[0].handle = courseAddEdit
tableItem.btnArray[0].handle = courseAddEdit
tableItem.btnArray[1].handle = courseAddEdit
// 类型管理
tableItem.btnArray[2].handle = (row) => {
    // console.log(row, 'row')
    requestType.courseId = row.id
    initTableDataType()
    addVisible.value = true
}
tableItem.btnArray[3].handle = (row) => {
    proxy.$modal.confirm("确定删除" + row.name || '' + '课程').then(() => {
        courseDelApi(row.id).then(res => {
            ElMessage.success('操作成功'); tableItem.pageInfo.paging()
        })
    })
}
// 价格管理
tableItem.btnArray[4].handle = (row) => {
    data.priceRequest.courseId = row.id || ''
    priceList()
    data.priceVisible = true
}
const priceList = () => {
    confListApi(data.priceRequest).then((res) => {
        data.priceTableData = res.rows
        data.priceTableData.map((item) => {
            item.static = 'detail'
        })
    })
}
</script>
<style lang="scss" scoped>
:deep(.el-table .el-table__cell) {
    height: 44px;
}

.add-type {
    float: right;
    margin-bottom: 20px;
}
</style>
